package com.jjx.trainingapi.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jjx.trainingapi.common.ErrorCode;
import com.jjx.trainingapi.common.MyException;
import com.jjx.trainingapi.entity.po.DcUser;
import com.jjx.trainingapi.entity.po.UserRecord;
import com.jjx.trainingapi.entity.po.UserRecordFavorite;
import com.jjx.trainingapi.entity.vo.UserInfoVo;
import com.jjx.trainingapi.mapper.DcUserMapper;
import com.jjx.trainingapi.service.DcUserService;
import com.jjx.trainingapi.service.UserRecordErrorService;
import com.jjx.trainingapi.service.UserRecordFavoriteService;
import com.jjx.trainingapi.service.UserRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author LoveHuahua
 * @date 2022年05月24日 1:10
 * @description believe in yourself
 */
@Service
public class DcUserServiceImpl extends ServiceImpl<DcUserMapper, DcUser> implements DcUserService {

    @Autowired
    UserRecordService recordService;
    @Autowired
    UserRecordFavoriteService favoriteService;
    @Autowired
    private UserRecordErrorService errorService;

    /**
     * 注册
     *
     * @param user
     */
    @Override
    public void register(DcUser user) {
        if (!StrUtil.isAllNotBlank(user.getUsername(), user.getPassword(), user.getNickName())) {
            throw new MyException(ErrorCode.USER_PASSWORD_EMPTY);
        }
        DcUser one = lambdaQuery().eq(DcUser::getUsername, user.getUsername()).one();
        if (one != null) {
            throw new MyException(ErrorCode.USER_HAS_EXIST);
        }
        if (StrUtil.isBlank(user.getAvatarUrl())){
            //如果是空的，默认头像
            user.setAvatarUrl("http://oss-training.jxwazx.cn/user_icon/1654790463928-logo.png");
        }
        save(user);
    }

    /**
     * 根据用户id查询用户所有信息
     *
     * @param userId
     * @return
     */
    @Override
    public UserInfoVo getUserInfo(int userId) {
        UserInfoVo userInfo = baseMapper.getUserInfo(userId);
        //查询错误数
        Integer errorCount = errorService.queryErrorCount(userId);
        //刷题总数
        Integer totalCount = recordService.lambdaQuery().eq(UserRecord::getUserId, userId).count().intValue();
        //收藏总数
        Integer favoriteCount = favoriteService.lambdaQuery().eq(UserRecordFavorite::getUserId, userId).count().intValue();
        //排名
        Integer totalCountRank = recordService.getTotalCountRank(userId);


        userInfo.setErrorCount(errorCount);
        userInfo.setFavoriteCount(favoriteCount);
        userInfo.setTotalCount(totalCount);
        if (totalCountRank != null){
            userInfo.setTotalCountRank(totalCountRank);
        }else{
            userInfo.setTotalCountRank(0);
        }
        return userInfo;
    }
}

